import {
    createRouter,
    createWebHashHistory,
    createWebHistory
} from 'vue-router';
import { useUserStore, useConfigStore } from '@/store';
import NProgress from 'nprogress';
import tool from '@/utils/tool';
import 'nprogress/nprogress.css';

import routes from './webRouter.js';

const title = import.meta.env.VITE_APP_TITLE;
const defaultRoutePath = '/';
const whiteRoute = [
    'login',
    'mineDoc',
    'interfaceList',
    'interfaceCode',
    'signature'
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    let toTitle = to.meta.title ? to.meta.title : to.name;
    const token = tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX);
    // 登录状态下
    if (token) {
        if (to.name === 'login') {
            next({ path: defaultRoutePath });
            return;
        }
        const configStore = useConfigStore();
        if (!userStore.user && userStore.user == undefined) {
            const data = await userStore.requestUserInfo();
            // data && next({ path: to.path, query: to.query })
            if (data.project_config) {
                document.title = `${toTitle} - ${data.project_config.title}`;
            }

            if (to.path == '/' || to.path == '/dashboard') {
                if (
                    data.roles &&
                    data.roles.length &&
                    (data.roles.includes('manager') ||
                        data.roles.includes('superAdmin'))
                ) {
                    next({ name: 'cloud:client', query: to.query });
                } else if (data.roles.includes('america')) {
                    next({ name: 'america:massProduction', query: to.query });
                } else {
                    next({ path: to.path, query: to.query });
                }
            } else {
                next({ path: to.path, query: to.query });
            }
            // next({ path: to.path, query: to.query });
        } else {
            document.title = `${toTitle} - ${configStore.$state.title}`;
            next();
        }
        // if (to.name === 'login') {
        //     next({ path: defaultRoutePath });
        //     return;
        // }

        // if (!userStore.user && userStore.user == undefined) {
        //     const data = await userStore.requestUserInfo();
        //     data && next({ path: to.path, query: to.query });
        // } else {
        //     next();
        // }
    } else {
        // 未登录的情况下允许访问的路由
        document.title = '登录';
        if (!whiteRoute.includes(to.name)) {
            next({ name: 'login', query: { redirect: to.fullPath } });
        } else {
            next();
        }
    }
});

router.afterEach((to, from) => {
    NProgress.done();
});

router.onError((error) => {
    console.log(error);
    NProgress.done();
});

export default router;
